package com.tianshi.user.service.impl;

import com.tianshi.entity.UserAddresses;
import com.tianshi.user.mapper.UserAddressMapper;
import com.tianshi.user.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAddressesServiceImpl implements UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;

    @Override
    public List<UserAddresses> searchByUserId(Long userId) {
        return userAddressMapper.searchByUserId(userId);
    }
    //根据地址id删除地址
    @Override
    public int deleteById(Long addressId) {
        int row = userAddressMapper.deleteById(addressId);
        return row;
    }
    //修改地址信息
    @Override
    public int updateAddress(UserAddresses userAddresses) {
        //判断该地址是否要设置为默认地址
        if(userAddresses.getIsDefault()){
            //将该用户的所有地址设置为非默认地址
            userAddressMapper.updateDefault(userAddresses.getUserId());
        }
        //修改地址信息
        int row = userAddressMapper.updateAddress(userAddresses);
        return row;
    }
    //新增地址
    @Override
    public int addAddress(UserAddresses userAddresses) {
        //判断该地址是否存在 (根据addressId和地址信息判断)
//        if( userAddressMapper.searchByAddressId(userAddresses.getAddressId()) != null){
            //判断该地址是否要设置为默认地址
            if(userAddresses.getIsDefault()){
                //将该用户的所有地址设置为非默认地址
                userAddressMapper.updateDefault(userAddresses.getUserId());
            }
        //}
        //插入地址
        int row = userAddressMapper.insertAddress(userAddresses);
        return row;
    }
}
